import React, { useEffect, useState } from "react";
import {
  Breadcrumb,
  Card,
  Radio,
  Form,
  Select,
  DatePicker,
  Button,
  Table,
  Space,
  Tag,
} from "antd";
import { Link } from "react-router-dom";
import locale from "antd/es/date-picker/locale/zh_CN";
import { ExportOutlined, DeleteOutlined } from "@ant-design/icons";
import "./index.scss";
import { useChannel } from "@/hooks/useChannel";
import { getArticleListAPI } from "@/api/article";

const { Option } = Select;
const { RangePicker } = DatePicker;

const columns = [
  {
    title: "序号",
    dataIndex: "",
    key: "index",
    align: "center",
  },
  {
    title: "封面",
    dataIndex: "cover",
    key: "cover",
    align: "center",
    render: (cover) => (cover.images.length > 0 && cover.images ?
      (<img src={cover.images[0]} alt="" style={{ width: '50px', height: '50px' }} />) :
      (<span style={{color: '#999', fontSize: '12px', height: '50px' , display: 'inline-block'}}>暂无封面</span>))
  },
  {
    title: "标题",
    dataIndex: "title",
    key: "title",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    align: "center",
    render: (status) => status = 2 ? (<Tag color="success" style={{ margin: '0 auto' }}>审核通过</Tag>)
      : (<Tag color="warning" style={{margin: '0 auto'}}>待审核</Tag>)
  },
  {
    title: "发布时间",
    dataIndex: "pubdate",
    key: "pubdate",
    align: "center",
  },
  {
    title: "阅读数",
    dataIndex: "read_count",
    key: "read_count",
    align: "center",
  },
  {
    title: "评论数",
    dataIndex: "comment_count",
    key: "comment_count",
    align: "center",
  },
  {
    title: "点赞数",
    dataIndex: "like_count",
    key: "like_count",
    align: "center",
  },
  {
    title: "操作",
    // dataIndex: 'likeCount',
    key: "likeCount",
    align: "center",
    render: () => (
      <Space>
        <Button
          type="primary"
          size="small"
          shape="circle"
          icon={<ExportOutlined />}
        />
        <Button
          type="primary"
          size="small"
          danger
          shape="circle"
          icon={<DeleteOutlined />}
        />
      </Space>
    ),
  },
];

function Article() {
    // 1。准备相应的请求参数
  const [ reqData, setReqData ] = useState({
    status: '',
    channel_id: '',
    begin_pubdate: '',
    end_pubdate: '',
    page: 1, //当前页数
    per_page: 10
  })
  // 获取文章列表接口
  const [ articleList, setArticleList ] = useState([])
  useEffect(() => {
      const getArticleList = async () => {
      const res = await getArticleListAPI(reqData)
      console.log(res.data);
      setArticleList(res.data.results)
      setCount(res.data.total_count)
    }
    getArticleList()
  },[reqData])
 
  const { channelList } = useChannel();
  // 查询总条数
  const [count, setCount] = useState(0)
  // 筛选功能实现

  const onFinish = (formValue) => {
    console.log(formValue);
    setReqData({
      ...reqData,
      status: formValue.type,
      channel_id: formValue.channel_id,
      begin_pubdate: formValue.range[0].format('YYYY-MM-DD'),
      end_pubdate: formValue.range[1].format('YYYY-MM-DD'),
    })
  }
  // 分页
  const onPageChange = (val) => {
    setArticleList([])
    setReqData({
      ...reqData,
      page: val
     })
  }
  const [pageSize, setPageSize] = useState(reqData.per_page); // 新增管理每页显示条数的状态
  const onShowSizeChange = (current, size) => {
    setPageSize(size); // 更新每页显示条数
    setReqData((prev) => ({
      ...prev,
      per_page: size, // 更新请求的per_page参数
      page: 1, // 每次更改每页条数时重置到第一页
    }));
  };
  return (
    <div>
      <Card className="articleCard">
        {/* 面包屑 */}
        <div className="article-bread">
          <Breadcrumb
            separator=">"
            items={[
              { title: "文章管理" },
              { title: <Link to="/article">首页</Link> },
            ]}
          />
        </div>
        {/* 筛选部分 */}
        <div className="article" style={{ marginTop: "30px" }}>
          <Form autoComplete="off" onFinish={onFinish}>
            {/* 状态 */}
            <Form.Item label="状态" name="type">
              <Radio.Group>
                <Radio value={0}>全部</Radio>
                <Radio style={{ margin: "0 30px" }} value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 频道 */}
            <Form.Item label="频道" name="channel_id" style={{ width: "25%" }}>
              <Select placeholder="请选择" size="small">
                {channelList.map((item) => (
                  <Option value={item.id} key={item.id}> {item.name}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="选择时间" style={{ width: "25%" }} name="range" >
              <RangePicker locale={locale}> </RangePicker>
            </Form.Item>
            <Form.Item style={{ width: '100%'}}>
              <Button
                type="primary"
                htmlType="提交文章"
                size="small"
                style={{ fontSize: "12px" }}
              >
                {" "}
                点击筛选
              </Button>
              <span>根据筛选条件共查询到 <i style={{fontStyle: "normal", color: 'red', fontWeight: '700'}}>{ count }</i> 条结果</span>
            </Form.Item>
          </Form>
        </div>
        {/* 表格部分 */}
        <div className="article-table">
          <Table dataSource={articleList} columns={columns} rowKey="id" pagination={{
            current: reqData.page, // 添加当前页
            pageSize: pageSize, // 使用pageSize状态
            total: count, 
            onChange: onPageChange,
            showSizeChanger: true, // 显示选择每页条数
            pageSizeOptions: ['4', '5', '8', '10'], // 可选的每页显示条数
            onShowSizeChange: onShowSizeChange
          }}></Table>
        </div>
      </Card>
      {/* 表格区域 */}
    </div>
  );
}

export default Article;
